import { _decorator, Animation, Component, director, instantiate, Node, Prefab, v3 } from 'cc';
import { events } from '../../Enums';
import ResourceManger from '../../ResourceManger';
import { ResourcePool } from '../../ResourcePool';
import { LvLStorage } from '../../LvLStorage';
const { ccclass, property } = _decorator;

@ccclass('House')
export class House extends Component {
    private instructEff:Node=null;
    @property(Node)
    roomElements:Node[] = [];
    @property
    houseId:number = 0;

    private houseData:any = null;

    start() {

    }

    protected onLoad(): void {
        director.on(events.build_instruct,this.onBuildInstruct,this);
        this.showInnerRoom();
    }

    protected showInnerRoom(): void {
        let house_info:any = LvLStorage.get_house_info();
        if(this.houseId < house_info["build_id"]){

        }else{
            for(let i = 0;i < house_info["stage"].length;i++){
                for(let j = 0;j < house_info["stage"][i];j++){
                    let eleNode:Node = this.roomElements[i];
                    let ele_stage:Node = eleNode.getChildByName(`ele_stage_${j+1}`);
                    ele_stage.active = true;
                }
            }
        }
    }


    protected onBuildInstruct(data: any): void {
        // data:any = {
        //     "id":this.house_id,
        //     "ele":_idx,
        //     "stage":house_info["stage"][_idx]
        // }
        this.houseData = data;
        let instructEffPrefab = ResourcePool.instance.get_prefab("instructEff");
        if(this.instructEff){
            this.node.removeChild(this.instructEff);
            this.instructEff.destroy();
        }
        this.instructEff = instantiate(instructEffPrefab);
        this.node.addChild(this.instructEff);
        console.log(this.roomElements[this.houseData.ele].getPosition());
        let pos = this.roomElements[this.houseData.ele].getPosition();
        this.instructEff.setPosition(v3(pos.x+310,pos.y+430,pos.z))
        this.instructEff.getComponent(Animation).on(Animation.EventType.FINISHED,this.onInstructEffFinished,this);
    }

    protected onInstructEffFinished(): void {
        this.node.removeChild(this.instructEff);
        this.instructEff.destroy();
        this.roomElements[this.houseData.ele].getChildByName(`ele_stage_${this.houseData.stage}`).active = true;
    }

    update(deltaTime: number) {
        
    }
}

